package com.leet.code.simple_array;

import java.util.Arrays;

/**
 * @description:    1464.数组中两元素的最大乘积
 * @author: WYG
 * @time: 2021/1/4 17:29
 */

public class MaxProduct {
    public int maxProduct(int[] nums) {
        Arrays.sort(nums);
        return (nums[nums.length - 1] - 1) * (nums[nums.length - 2] - 1);
    }

    public int fastest_maxProduct(int[] nums) {
        if(nums.length == 2) return (nums[0] - 1) * (nums[1] - 1);
        int max1 = nums[0], max2 = nums[1];
        for(int i = 2; i < nums.length; i++) {
            if(nums[i] > max1 || nums[i] > max2) {
                if(max1 >= max2) {
                    max2 = nums[i];
                }else {
                    max1 = nums[i];
                }
            }
        }
        return (max2 - 1) * (max1 - 1);
    }

    public int fast_maxProduct(int[] nums) {
        int res = 1;
        int[] temp = new int[1001];
        for (int x : nums) {
            temp[x]++;
        }
        int count = 0;
        for (int i = 1000; i > 0; i--) {
            if (temp[i] != 0 && count < 2) {
                for (int j = 0; j < temp[i]; j++) {
                    if (count == 2) {
                        break;
                    }
                    res = res * (i - 1);
                    count++;
                }
            }
        }
        return res;
    }

    public int few_memory_maxProduct(int[] nums) {
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > max) {
                max = nums[i];
            }
        }
        int res = 1;
        int[] temp = new int[max + 1];
        for (int x : nums) {
            temp[x]++;
        }
        int count = 0;
        for (int i = max; i > 0; i--) {
            if (temp[i] != 0 && count < 2) {
                for (int j = 0; j < temp[i]; j++) {
                    if (count == 2) {
                        break;
                    }
                    res = res * (i - 1);
                    count++;
                }
            }
        }
        return res;
    }
}
